use calamine::{open_workbook_auto, Reader, Range, Data};
use std::error::Error;
use std::collections::HashMap;

#[derive(Debug, Clone)]
pub struct Config {
    pub url: String,
    pub total_requests: usize,
    pub concurrency: usize,
    pub request_interval: u64,
    pub timeout: u64,
    pub report_interval: u64,
    pub data_file: String,
    pub endpoints_file: String,
    pub headers: HashMap<String, String>, // 请求头
    pub test_data: Vec<TestData>, // 接口测试数据
}

#[derive(Debug, Clone)]
pub struct TestData {
    pub method: String,    // 请求方法（GET、POST 等）
    pub path: String,      // 请求路径
    pub data: String,      // 请求数据（JSON 格式）
}

impl Config {
    pub fn from_excel(file_path: &str) -> Result<Self, Box<dyn Error>> {
        let mut workbook = open_workbook_auto(file_path)?;

        // 读取配置项
        let range_option = workbook.worksheet_range("Config");
        let range = match range_option {
            Ok(Some(r)) => r,
            Ok(None) => return Err("无法找到名为 'Config' 的工作表".into()),
            Err(_) => return Err("读取工作表时出错".into()),
            _ => {}
        };

        let mut url = String::new();
        let mut total_requests = 0;
        let mut concurrency = 0;
        let mut request_interval = 0;
        let mut timeout = 0;
        let mut report_interval = 0;
        let mut data_file = String::new();
        let mut endpoints_file = String::new();

        for row in range.rows() {
            if let Some(val) = row.get(1) {
                match row.get(0).unwrap_or(&"") {
                    "url" => url = val.get_string().unwrap_or_default().to_string(),
                    "total_requests" => total_requests = val.get_int().unwrap_or(0) as usize,
                    "concurrency" => concurrency = val.get_int().unwrap_or(0) as usize,
                    "request_interval" => request_interval = val.get_int().unwrap_or(0) as u64,
                    "timeout" => timeout = val.get_int().unwrap_or(0) as u64,
                    "report_interval" => report_interval = val.get_int().unwrap_or(0) as u64,
                    "data_file" => data_file = val.get_string().unwrap_or_default().to_string(),
                    "endpoints_file" => endpoints_file = val.get_string().unwrap_or_default().to_string(),
                    _ => {},
                }
            }
        }

        // 读取请求头
        let mut headers = HashMap::new();
        if let Some(sheet) = workbook.worksheet_range("Headers") {
            if let Some(sheet_range) = sheet {
                for row in sheet_range.rows() {
                    if let (Some(header), Some(value)) = (row.get(0), row.get(1)) {
                        let header = header.get_string().unwrap_or_default().to_string();
                        let value = value.get_string().unwrap_or_default().to_string();
                        headers.insert(header, value);
                    }
                }
            }
        }

        // 读取接口测试数据
        let mut test_data = Vec::new();
        if let Some(sheet) = workbook.worksheet_range("TestData") {
            if let Some(sheet_range) = sheet {
                for row in sheet_range.rows() {
                    if let (Some(method), Some(path), Some(data)) = (row.get(1), row.get(2), row.get(3)) {
                        let method = method.get_string().unwrap_or_default().to_string();
                        let path = path.get_string().unwrap_or_default().to_string();
                        let data = data.get_string().unwrap_or_default().to_string();

                        test_data.push(TestData {
                            method,
                            path,
                            data,
                        });
                    }
                }
            }
        }

        // 返回 Config 配置对象
        Ok(Config {
            url,
            total_requests,
            concurrency,
            request_interval,
            timeout,
            report_interval,
            data_file,
            endpoints_file,
            headers,
            test_data,
        })
    }
}
